package MiddlePractice;

import java.util.LinkedList;

import org.junit.Test;

public class Demo200 {
//	200. 岛屿数量
//	给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
//
//	岛屿总是被水包围，并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
//
//	此外，你可以假设该网格的四条边均被水包围。
	
	private int islandNum = 0;
	
	public int numIslands(char[][] grid) {
		int m = grid.length;
		int n = grid[0].length;
		boolean[][] visited = new boolean[m][n];
		
		for(int i=0; i<m; i++) {
			for(int j=0; j<n; j++) {
				detect(grid, visited, i, j);
			}
		}
		
		return islandNum;
    }
	
	private void detect(char[][] grid, boolean[][] visited, int x, int y) {
		if(visited[x][y]) {
			return;
		}
		
		if(grid[x][y] == '0') {
			visited[x][y] = true;
			return;
		}
		
		LinkedList<int[]> queue = new LinkedList<>();
		int[][] directs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
		
		int m = grid.length;
		int n = grid[0].length;
		queue.offer(new int[] {x, y});
		visited[x][y] = true;
		
		while(!queue.isEmpty()) {
			int size = queue.size();
			for(int i=0; i<size; i++) {
				
				int[] center = queue.poll();
				
				for(int[] direct : directs) {
					int newX = direct[0] + center[0];
					int newY = direct[1] + center[1];
					if(newX >=0 && newX < m && newY >=0 && newY < n && 
							!visited[newX][newY] && grid[newX][newY] == '1') {
						queue.offer(new int[] {newX, newY});
						visited[newX][newY] = true;
					}
				}
			}
		}
		islandNum++;
	}
	
	
	@Test
	public void test_200() {
		char[][] grid = {
		        {'1','1','1','1','0'},
		        {'1','1','0','1','0'},
		        {'1','1','0','0','0'},
		        {'0','0','0','0','0'}
		      };
		System.out.println(numIslands(grid));
	}
	
}
